// pages/publish-demand/publish-demand.ts
import { createDemand } from '../../../api/publish.js'
import { uploadTechParams } from '../../../api/upload.js'
import { getCategoryNames, getProductsByCategory, getDemandCategoryNames } from '../../../config/product-categories.js'
import { PAGE_PUBLISH_SELECT, PAGE_DEMAND_DETAIL, goToPage } from '../../../config/pages.js'
import userManager from '../../../utils/userManager.js'

interface FormData {
  product_category: string;
  product_name: string;
  product_model: string;
  category: string; // 新增分类字段，用于筛选
  remark: string;
  province: string;
  city: string;
  district: string;
  province_id: number;
  city_id: number;
  district_id: number;
  detail_address: string;
  contact_name: string;
  contact_phone: string;
  contact_email: string;
}

Page({
  data: {
    // 表单数据
    formData: {
      product_category: '',
      product_name: '',
      product_model: '',
      category: '', // 新增分类字段，用于筛选
      remark: '',
      province: '',
      city: '',
      district: '',
      province_id: 0,
      city_id: 0,
      district_id: 0,
      detail_address: '',
      contact_name: '',
      contact_phone: '',
      contact_email: ''
    } as FormData,
    
    // 求购分类选择器（材料/加工）
    demandCategoryList: getDemandCategoryNames(),
    showDemandCategoryPicker: false,
    demandCategoryIndex: 0,
    
    // 产品类别选择器
    categoryList: getCategoryNames(),
    showCategoryPicker: false,
    categoryIndex: 0,
    
    // 产品名称选择器
    productList: [] as string[],
    showProductPicker: false,
    productIndex: 0,
    
    // 技术参数上传
    techParamsFile: null as any,
    techParamsFileName: '',
    techParamsUrl: '',
    uploadingTechParams: false,
    
    // 提交状态
    submitting: false,
    
    // 发布成功后的单据ID
    publishedId: 0
  },

  onLoad() {
    this.loadUserInfo();
  },

  // 加载用户信息并填入表单
  async loadUserInfo() {
    try {
      const userInfo = await userManager.getUserInfo() as any;
      if (userInfo) {
        this.setData({
          'formData.contact_name': userInfo.real_name || userInfo.nickname || '',
          'formData.contact_phone': userInfo.phone || ''
        });
      }
    } catch (error) {
      console.error('加载用户信息失败:', error);
    }
  },

  // 输入框变化
  onInputChange(e: any) {
    const field = e.currentTarget.dataset.field;
    const value = e.detail.value;
    this.setData({
      [`formData.${field}`]: value
    });
  },

  // 显示求购分类选择器
  showDemandCategoryPicker() {
    this.setData({
      showDemandCategoryPicker: true
    });
  },

  // 求购分类选择器变化
  onDemandCategoryChange(e: any) {
    const index = e.detail.value[0];
    this.setData({
      demandCategoryIndex: index
    });
  },

  // 求购分类选择器取消
  onDemandCategoryCancel() {
    this.setData({
      showDemandCategoryPicker: false
    });
  },

  // 求购分类选择器确认
  onDemandCategoryConfirm() {
    const index = this.data.demandCategoryIndex || 0;
    const category = this.data.demandCategoryList[index];
    this.setData({
      showDemandCategoryPicker: false,
      'formData.category': category
    });
  },

  // 显示产品类别选择器
  showCategoryPicker() {
    this.setData({
      showCategoryPicker: true
    });
  },

  // 显示产品名称选择器
  showProductPicker() {
    this.setData({
      showProductPicker: true
    });
  },

  // 产品类别选择器变化
  onCategoryChange(e: any) {
    const index = e.detail.value[0];
    this.setData({
      categoryIndex: index
    });
  },

  // 产品类别选择器取消
  onCategoryCancel() {
    this.setData({
      showCategoryPicker: false
    });
  },

  // 产品类别选择器确认
  onCategoryConfirm() {
    const index = this.data.categoryIndex || 0;
    const category = this.data.categoryList[index];
    const products = getProductsByCategory(category);
    this.setData({
      showCategoryPicker: false,
      'formData.product_category': category,
      'formData.product_name': '', // 清空产品名称
      productList: products,
      productIndex: 0
    });
  },

  // 产品名称选择器变化
  onProductChange(e: any) {
    const index = e.detail.value[0];
    this.setData({
      productIndex: index
    });
  },

  // 产品名称选择器取消
  onProductCancel() {
    this.setData({
      showProductPicker: false
    });
  },

  // 产品名称选择器确认
  onProductConfirm() {
    const index = this.data.productIndex || 0;
    const product = this.data.productList[index];
    this.setData({
      showProductPicker: false,
      'formData.product_name': product
    });
  },


  // 地址选择变化
  onAddressChange(e: any) {
    const { address } = e.detail;
    if (address) {
    this.setData({
        'formData.province': address.province,
        'formData.city': address.city,
        'formData.district': address.district,
        'formData.province_id': address.province_id,
        'formData.city_id': address.city_id,
        'formData.district_id': address.district_id
      });
    }
  },

  // 上传技术参数
  async uploadTechParams() {
    try {
      const res = await wx.chooseMessageFile({
        count: 1,
        type: 'file',
        extension: ['pdf', 'jpg', 'png']
      }) as any;
      
      const file = res.tempFiles[0];
      
      // 检查文件大小（最大10MB）
      if (file.size > 10 * 1024 * 1024) {
        wx.showToast({
          title: '文件大小不能超过10MB',
          icon: 'none'
        });
        return;
      }
      
      // 显示上传中
      this.setData({
        uploadingTechParams: true,
        techParamsFileName: file.name
      });
      
      wx.showLoading({
        title: '上传中...'
      });
      
      // 调用上传API
      const uploadResult = await uploadTechParams(file.path, () => {}, file.name);
      
      wx.hideLoading();
      
      if (uploadResult.code === 200 && uploadResult.data) {
        this.setData({
          techParamsUrl: uploadResult.data.url,
          techParamsFileName: uploadResult.data.name || file.name,
          uploadingTechParams: false
        });
        
        wx.showToast({
          title: '技术参数上传成功',
          icon: 'success'
        });
      } else {
        throw new Error(uploadResult.msg || '上传失败');
      }
    } catch (error: any) {
      console.error('上传技术参数失败:', error);
      this.setData({
        uploadingTechParams: false
      });
      wx.hideLoading();
      wx.showToast({
        title: typeof(error) === 'string' ? error : (error?.errMsg || error?.message || '上传失败'),
        icon: 'none'
      });
    }
  },
  
  // 删除技术参数
  removeTechParams() {
    this.setData({
      techParamsFile: null,
      techParamsFileName: '',
      techParamsUrl: ''
    });
  },

  // 表单验证
  validateForm(): boolean {
    const { formData } = this.data;
    
    if (!formData.category) {
      wx.showToast({
        title: '请选择求购分类',
        icon: 'none'
      });
      return false;
    }
    
    if (!formData.product_category) {
      wx.showToast({
        title: '请选择产品类别',
        icon: 'none'
      });
      return false;
    }
    
    if (!formData.product_name) {
      wx.showToast({
        title: '请选择产品名称',
        icon: 'none'
      });
      return false;
    }
    
    if (!formData.product_model.trim()) {
      wx.showToast({
        title: '请输入产品型号',
        icon: 'none'
      });
      return false;
    }
    
    if (!formData.province) {
      wx.showToast({
        title: '请选择所在地',
        icon: 'none'
      });
      return false;
    }
    
    if (!formData.contact_name.trim()) {
      wx.showToast({
        title: '请输入联系人姓名',
        icon: 'none'
      });
      return false;
    }
    
    if (!formData.contact_phone.trim()) {
      wx.showToast({
        title: '请输入联系电话',
        icon: 'none'
      });
      return false;
    }

    return true;
  },

  // 提交表单
  async submitForm() {
    if (!this.validateForm()) {
      return;
    }

    this.setData({ submitting: true });

    try {
      // 准备提交数据
      const submitData: any = {
        ...this.data.formData
      };
      
      // 添加技术参数信息（如果有上传）
      if (this.data.techParamsUrl) {
        submitData.tech_params_atts = JSON.stringify([{
          url: this.data.techParamsUrl,
          name: this.data.techParamsFileName
        }]);
        submitData.tech_params_file_name = this.data.techParamsFileName;
      }

      // 调用API创建求购
      const result = await createDemand(submitData);
      
      if (result.status === 200) {
        wx.hideLoading();
        // 保存发布成功的单据ID
        if (result.data && result.data.id) {
          this.setData({
            publishedId: result.data.id
          });
        }
        this.showPublishSuccessModal();
      } else {
        wx.hideLoading();
        wx.showToast({
          title: result.msg || '发布失败',
          icon: 'none'
        });
      }
    } catch (error: any) {
      console.error('发布求购失败:', error);
      wx.hideLoading();
      wx.showToast({
        title: typeof(error) === 'string' ? error : (error?.msg || '发布失败，请重试'),
        icon: 'none'
      });
    } finally {
      this.setData({ submitting: false });
    }
  },

  // 显示发布成功模态框
  showPublishSuccessModal() {
    wx.showModal({
      title: '发布完成',
      content: '您的求购信息已成功发布，等待供应商报价',
      showCancel: true,
      cancelText: '查看详情',
      confirmText: '继续发布',
      success: (res) => {
        if (res.confirm) {
          // 继续发布 - 使用switchTab跳转到发布选择页
          goToPage(PAGE_PUBLISH_SELECT, {}, 'switchTab');
        } else if (res.cancel) {
          // 查看详情 - 跳转到求购详情页，携带ID
          if (this.data.publishedId) {
            goToPage(PAGE_DEMAND_DETAIL, { id: this.data.publishedId }, 'redirectTo');
          } else {
            // 如果没有ID，返回上一页
            wx.navigateBack();
          }
        }
      }
    });
  }
});